<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.key"
          placeholder="参数名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button
         
          type="primary"
          @click="addOrUpdateHandle()"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('goods:goods:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="goodsId"
        header-align="center"
        align="center"
        label="商品id"
      >
      </el-table-column>
      <el-table-column
        prop="goodsName"
        header-align="center"
        align="center"
        label="商品名称"
      >
      </el-table-column>
      <el-table-column
        prop="goodsTitle"
        header-align="center"
        align="center"
        label="商品标题"
      >
      </el-table-column>
      <el-table-column prop="goodsImg"  header-align="center"  align="center"  label="商品图片">
       <template slot-scope="scope">
          <img :src="scope.row.goodsImg" width="50px">
        </template>
      </el-table-column> 
      <el-table-column
        prop="goodsDetail"
        header-align="center"
        align="center"
        label="商品详细介绍"
      >
      </el-table-column>
      <el-table-column
        prop="goodsPrice"
        header-align="center"
        align="center"
        label="商品单价"
      >
      </el-table-column>
      <el-table-column
        prop="goodsStock"
        header-align="center"
        align="center"
        label="商品库存，-1表示没有限制"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.goodsId)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.goodsId)"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="miaoaddOrUpdateHandle(scope.row.goodsId)"
            >添加秒杀活动</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="kanaddOrUpdateHandle(scope.row.goodsId)"
            >添加砍价活动</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>
    <!-- <MiaoAddOrUpdate v-if="miaoaddOrUpdateVisible" ref="miaoAddOrUpdate" @refreshDataList="getDataList"></MiaoAddOrUpdate> -->

    <el-dialog
      :title="!mdataForm.miaoId ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
     {{this.mdataForm}}<br>
      <el-form
        :model="mdataForm"
        :rules="dataRule"
        ref="mdataForm"
        @keyup.enter.native="mdataFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="商品id" prop="goodsId">
          <el-input v-model="mdataForm.goodsId" placeholder="商品id"></el-input>
        </el-form-item>
        <el-form-item label="秒杀价" prop="goodsPrice">
          <el-input
            v-model="mdataForm.goodsPrice"
            placeholder="秒杀价"
          ></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="stockCount">
          <el-input
            v-model="mdataForm.stockCount"
            placeholder="库存数量"
          ></el-input>
        </el-form-item>
        <el-form-item label="秒杀开始时间" prop="startDate">
          <el-date-picker
            v-model="mdataForm.startDate"
            type="datetime"
            placeholder="秒杀开始时间"
            value-format='yyyy-MM-dd HH:mm:ss'
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="秒杀结束时间" prop="endDate">
          <el-date-picker
            v-model="mdataForm.endDate"
            type="datetime"
            placeholder="秒杀结束时间"
            value-format='yyyy-MM-dd HH:mm:ss'
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="mdataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    



     <el-dialog
    :title="!dataFormkan.bid ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visiblekan">
    {{dataFormkan}}<br>
    <el-form :model="dataFormkan" :rules="dataRulekan" ref="dataFormkan" @keyup.enter.native="dataFormkanSubmit()" label-width="80px">
    <el-form-item label="商品编号" prop="gid">
      <el-input v-model="dataFormkan.gid" placeholder="商品编号"></el-input>
    </el-form-item>
    <el-form-item label="商品名称" prop="gname">
      <el-input v-model="dataFormkan.gname" placeholder="商品名称"></el-input>
    </el-form-item>
        <el-form-item label="秒杀开始时间" prop="bstartDate">
          <el-date-picker
            v-model="dataFormkan.bstartdate"
            type="datetime"
            placeholder="砍价开始时间"
            value-format='yyyy-MM-dd HH:mm:ss'
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="砍价结束时间" prop="bendDate">
          <el-date-picker
            v-model="dataFormkan.benddate"
            type="datetime"
            placeholder="秒杀结束时间"
            value-format='yyyy-MM-dd HH:mm:ss'
          >
          </el-date-picker>
        </el-form-item>
    <el-form-item label="原价" prop="gprice">
      <el-input v-model="dataFormkan.gprice" placeholder="原价"></el-input>
    </el-form-item>
    <el-form-item label="低价" prop="bjprice">
      <el-input v-model="dataFormkan.bjprice" placeholder="低价"></el-input>
    </el-form-item>
    {{count}}当前库存量
    <el-form-item label="砍价库存" prop="bcount">
      <el-input v-model="dataFormkan.bcount" placeholder="砍价库存"></el-input>
    </el-form-item>
    <el-form-item label="规则" prop="brules">
   
       <el-radio v-model="dataFormkan.brules" label="1">方案1</el-radio>
       <el-radio v-model="dataFormkan.brules" label="2">方案2</el-radio>
    </el-form-item>
   
      <span v-if="dataFormkan.brules==1">
       <el-form-item label="最多砍几刀" prop="countorlow">
        <el-input v-model="dataFormkan.countorlow" placeholder="最多砍几刀"></el-input> 

         </el-form-item>
      </span>
      <span v-if="dataFormkan.brules==2">
        <el-form-item label="最多砍多少钱" prop="countorlow">
        <el-input v-model="dataFormkan.countorlow" placeholder="最多砍多少钱"></el-input> 
        </el-form-item>
      </span>
   
    <el-form-item label="详情描述" prop="detail">
      <el-input v-model="dataFormkan.detail" placeholder="详情描述"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visiblekan = false">取消</el-button>
      <el-button type="primary" @click="dataFormkanSubmit()">确定</el-button>
    </span>
  </el-dialog>
  </div>
  
</template>


<script>
import AddOrUpdate from "./goods-add-or-update";

export default {
  data() {
    return {
      
      dataForm: {
        key: "",
      },
      mdataForm: {
        miaoId: 0,
        goodsId: "",
        goodsPrice: "",
        stockCount: "",
        startDate: "",
        endDate: "",
      },
       dataFormkan: {
          bid: 0,
          gid: '', 
          bcount:0,
          gname: '',
          bstartdate: '',
          benddate: '',
          gprice: '',
          bjprice: '',
          brules: '',
          countorlow: '',
          detail: ''
        },
      visible: false,
      visiblekan: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      miaoaddOrUpdateVisible: false,
      count: "",
      
      dataRule: {
        goodsId: [
          { required: true, message: "商品id不能为空", trigger: "blur" },
        ],
        goodsPrice: [
          { required: true, message: "秒杀价不能为空", trigger: "blur" },
        ],
        stockCount: [
          { required: true, message: "库存数量不能为空", trigger: "blur" },
        ],
        startDate: [
          { required: true, message: "秒杀开始时间不能为空", trigger: "blur" },
        ],
        endDate: [
          { required: true, message: "秒杀结束时间不能为空", trigger: "blur" },
        ],
      },
      
      dataRulekan: {
          gid: [
            { required: true, message: '商品编号不能为空', trigger: 'blur' }
          ],
          gname: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' }
          ],
          bstartdate: [
            { required: true, message: '开始时间不能为空', trigger: 'blur' }
          ],
          benddate: [
            { required: true, message: '结束时间不能为空', trigger: 'blur' }
          ],
          gprice: [
            { required: true, message: '原价不能为空', trigger: 'blur' }
          ],
          bjprice: [
            { required: true, message: '低价不能为空', trigger: 'blur' }
          ],
          brules: [
            { required: true, message: '规则不能为空', trigger: 'blur' }
          ],
          countorlow: [
            { required: true, message: '砍几刀或者能砍多少钱不能为空', trigger: 'blur' }
          ],
          detail: [
            { required: true, message: '详情描述不能为空', trigger: 'blur' }
          ]
        }
    }; 
  },
  watch: {
    'dataFormkan.bcount'(ne){

      if(this.count<ne){
        console.log(ne)
        this.dataFormkan.bcount=0
        alert("砍价库存不可超过总库存量")
      }

    }


  },
    getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
},
  components: {
    
    // MiaoAddOrUpdate,
    AddOrUpdate,
  },
  activated() {
    this.getDataList();
  },
  
  methods: {
    miaoaddOrUpdateHandle(id) {
      this.mdataForm.miaoId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
      
        if (this.mdataForm.miaoId) {
          this.$http({
            url: this.$http.adornUrl(
              `/goods/goods/info/${this.mdataForm.miaoId}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.mdataForm.miaoId=0
              this.mdataForm.goodsId = data.goods.goodsId;
              this.mdataForm.goodsPrice = data.goods.goodsPrice;
              this.mdataForm.stockCount = data.goods.goodsStock;
            }
          });
        }
      });
    },
    kanaddOrUpdateHandle (id) {
        this.dataFormkan.bid = id || 0
        this.visiblekan = true
        this.$nextTick(() => {
         
          if (this.dataFormkan.bid) {
            this.$http({
            url: this.$http.adornUrl(
              `/goods/goods/info/${this.dataFormkan.bid}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataFormkan.bid=0
              this.dataFormkan.gid = data.goods.goodsId;
              this.dataFormkan.gprice= data.goods.goodsPrice;
              this.dataFormkan.gname=data.goods.goodsName;
              this.count=data.goods.goodsStock;
            }
          });
          }
        })
      },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/goods/goods/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    //  miaoaddOrUpdateHandle (id) {
    //   this.miaoaddOrUpdateVisible = true

    //      this.$nextTick(() => {
    //     this.$refs.MiaoAddOrUpdate.init(id, couponStatus)
    //   })
    mdataFormSubmit() {
      this.$refs["mdataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/activity/miaoactivity/${
                 "save" 
              }`
            ),
            method: "post",
            data: this.$http.adornData({
              miaoId: this.mdataForm.miaoId || undefined,
              goodsId: this.mdataForm.goodsId,
              goodsPrice: this.mdataForm.goodsPrice,
              stockCount: this.mdataForm.stockCount,
              startDate: this.mdataForm.startDate,
              endDate: this.mdataForm.endDate,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  dataFormkanSubmit () {
        this.$refs['dataFormkan'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/bargain/bargain/${!this.dataFormkan.bid ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'bid': this.dataFormkan.bid || undefined,
                'gid': this.dataFormkan.gid,
                'gname': this.dataFormkan.gname,
                'bcount': this.dataFormkan.bcount,
                'bstartdate': this.dataFormkan.bstartdate,
                'benddate': this.dataFormkan.benddate,
                'gprice': this.dataFormkan.gprice,
                'bjprice': this.dataFormkan.bjprice,
                'brules': this.dataFormkan.brules,
                'countorlow': this.dataFormkan.countorlow,
                'detail': this.dataFormkan.detail
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visiblekan = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
    // },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },

    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.goodsId;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/goods/goods/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
  },
};
</script>
